//
//  ExercisesAnswerCardViewController.m
//  ShowYork
//
//  Created by hxh on 2020/9/10.
//  Copyright © 2020 hxh. All rights reserved.
//

#import "ExercisesAnswerCardViewController.h"
#import "ExercisesAnswerResultViewController.h"
#import "ExercisesAnswerCardItemCell.h"
#import "ExercisesAnswerResultItemCell.h"
#import "ExercisesAnswerCardHeaderView.h"
#import "ExercisesNormalAlertView.h"
#import "ExercisesCardHeaderBarView.h"
#import "ExercieseQuestionItemModel.h"
#import "ExerciesePostCardArgModel.h"
#import "ExercieseCardAnswerModel.h"
#import "ExercisesPaperResultModel.h"
#import "ExercisesPageModel.h"
@interface ExercisesAnswerCardViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,ExercisesAnswerCardItemCellDelegate>
@property (nonatomic,strong)UICollectionView *collectionView;
@property (nonatomic,strong)UIButton *confirmBtn;
@property (nonatomic,strong)UILabel *mainTitle;
@property (nonatomic,strong)NSMutableArray *titleArray;
@property (nonatomic,strong)NSMutableArray *sourceArray;
@property (nonatomic,strong)ExerciesePostCardArgModel *argModel;

@property (nonatomic,assign)XHEnterCardType type;
@property (nonatomic,strong)CAGradientLayer *gradientLayer;


@property (nonatomic,strong)UIView *coverView;
@property (nonatomic,strong)UIImageView *coverRemindView;
@property (nonatomic,strong)UIImageView *coverRemoveView;

@property (nonatomic,strong)ExercisesCardHeaderBarView *headerView;

@property (nonatomic,strong)ExercisesPageModel *itemModel;

@property (nonatomic,strong)NSTimer *timer;
@property (nonatomic,assign)CGFloat timeSource;

@end

@implementation ExercisesAnswerCardViewController



- (CAGradientLayer *)gradientLayer{
    if (!_gradientLayer) {
        _gradientLayer =  [CAGradientLayer layer];
        _gradientLayer.frame = self.confirmBtn.bounds;
        _gradientLayer.endPoint = CGPointMake(0, 0);
        _gradientLayer.startPoint  = CGPointMake(1.0, 0);
        _gradientLayer.colors = @[(id)RGBA(119, 153, 255, 1).CGColor,(id)RGBA(86, 128, 250, 1).CGColor];
    }
    return _gradientLayer;
}

- (ExerciesePostCardArgModel *)argModel{
    if (!_argModel) {
        _argModel = [[ExerciesePostCardArgModel alloc]init];
    }
    return _argModel;
}

- (NSMutableArray *)sourceArray{
    if (!_sourceArray) {
        _sourceArray = [NSMutableArray array];
    }
    return _sourceArray;
}

- (NSMutableArray *)titleArray{
    if (!_titleArray) {
        _titleArray = [NSMutableArray array];
    }
    return _titleArray;
}

- (instancetype)initWithItemModel:(ExercisesPageModel *)itemModel enterType:(XHEnterCardType)type{
    if (self = [super init]) {
        self.type = type;
        self.itemModel = itemModel;
        self.timeSource = itemModel.cardTime;
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.timer invalidate];
    self.timer = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.isHideNavBar = YES;
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.collectionView registerClass:[ExercisesAnswerCardItemCell class] forCellWithReuseIdentifier:@"ExercisesAnswerCardItemCell"];
    [self.collectionView registerClass:[ExercisesAnswerResultItemCell class] forCellWithReuseIdentifier:@"ExercisesAnswerResultItemCell"];
    [self.collectionView registerClass:[ExercisesAnswerCardHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"ExercisesAnswerCardHeaderView"];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.bounces = NO;
       
    [self.view addSubview:self.collectionView];
    
    self.confirmBtn = [[UIButton alloc]init];
    [self.confirmBtn setTitle:@"提交练习并查看报告" forState:UIControlStateNormal];
    [self.confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.confirmBtn.titleLabel.font = font(18);
    self.confirmBtn.layer.cornerRadius = 22;
    self.confirmBtn.layer.masksToBounds = YES;
    self.confirmBtn.backgroundColor = [RPAppManager themColor];
    [self.confirmBtn addTarget:self action:@selector(confirmMethod) forControlEvents:UIControlEventTouchUpInside];
      
    [self.view addSubview:self.confirmBtn];
    

    self.mainTitle = [[UILabel alloc]init];
    self.mainTitle.textColor = RGBA(102, 102, 102, 102);
    self.mainTitle.font = font(12);
    [self.view addSubview:self.mainTitle];

    if (self.type != XHENTERCARDADD) {
        @zf_weakify(self)
        self.headerView = [[ExercisesCardHeaderBarView alloc]initWithCompleteBlock:^{
            @zf_strongify(self)
            if (self.type == XHENTERCARDRESULT || self.type == XHENETRCARDNORMAL) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }else{
                [self.navigationController popViewControllerAnimated:YES];
            }
        }];
        [self.view addSubview:self.headerView];
        
        [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(self.view);
            make.height.mas_equalTo(44 + GK_STATUSBAR_HEIGHT);
        }];
        [self.mainTitle mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view.mas_left).offset(16);
            make.top.equalTo(self.headerView.mas_bottom).offset(16);
        }];
    }else{
        
        [self.mainTitle mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view.mas_left).offset(16);
            make.top.equalTo(self.view).offset(16);
        }];
    }
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11,*)) {
            make.right.equalTo(self.view.mas_safeAreaLayoutGuideRight);
            make.left.equalTo(self.view.mas_safeAreaLayoutGuideLeft);
        }else{
            make.top.equalTo(self.view.mas_top);
            make.right.equalTo(self.view.mas_right);
            make.left.equalTo(self.view.mas_left);
        }
        make.top.equalTo(self.mainTitle.mas_bottom).offset(22);
        make.bottom.mas_equalTo(self.confirmBtn.mas_top).offset(-16);
    }];

    
    [self.confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11,*)) {
            make.right.equalTo(self.view.mas_safeAreaLayoutGuideRight).offset(-16);
            make.left.equalTo(self.view.mas_safeAreaLayoutGuideLeft).offset(16);
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-47 + GK_SAVEAREA_BTM);
        }else{
            make.right.equalTo(self.view.mas_right).offset(-16);
            make.left.equalTo(self.view.mas_left).offset(16);
            make.bottom.equalTo(self.view.mas_bottom).offset(-47 + GK_SAVEAREA_BTM);
        }
        make.height.mas_equalTo(44);
    }];
        
    if (self.itemModel.resultArray.count != 0) {
        [self dealDataSource];
    }
    
    [self.confirmBtn layoutIfNeeded];
    
    [self.confirmBtn.layer insertSublayer:self.gradientLayer atIndex:0];
    
    if (![[[NSUserDefaults standardUserDefaults]objectForKey:@"isFirstExercieseCard"]boolValue]) {
        [self setupCoverView];
    }
    
    // 定时器相关
    [self setupTimer];
}

- (void)setupCoverView{
    dispatch_async(dispatch_get_main_queue(), ^{
        self.coverView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH)];
        self.coverView.backgroundColor = RGBA(0, 0, 0, 0.7);
        [[UIApplication sharedApplication].keyWindow addSubview:self.coverView];
        self.coverRemoveView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"common_help_tag"]];
        [self.coverView addSubview:self.coverRemoveView];
        [self.coverRemoveView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.coverView).offset(-(200+GK_SAVEAREA_BTM));
            make.right.equalTo(self.coverView).offset(-18);
        }];
        self.coverRemoveView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(removeHelpView)];
        [self.coverRemoveView addGestureRecognizer:tap];
        self.coverRemindView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"exerciese_tag_next"]];
        [self.coverView addSubview:self.coverRemindView];
        if (self.sourceArray.count > 0){
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
            UICollectionViewLayoutAttributes *attributes = [self.collectionView layoutAttributesForItemAtIndexPath:indexPath];
            CGRect cellRect = attributes.frame;
            CGRect cellFrameInSuperview = [self.collectionView convertRect:cellRect toView:[self.coverView superview]];
            // 第一个路径
            UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0,kScreenW, kScreenH)];
            // 透明path
            UIBezierPath *path2 = [[UIBezierPath bezierPathWithRoundedRect:CGRectMake(cellFrameInSuperview.origin.x, cellFrameInSuperview.origin.y,cellFrameInSuperview.size.width,cellFrameInSuperview.size.height) cornerRadius:cellFrameInSuperview.size.width * 0.5] bezierPathByReversingPath];
            [path appendPath:path2];
            // 绘制透明区域
            CAShapeLayer *shapeLayer = [CAShapeLayer layer];
            shapeLayer.path = path.CGPath;
            [self.coverView.layer setMask:shapeLayer];
            [self.coverRemindView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(self.coverView).offset(CGRectGetMaxY(cellFrameInSuperview));
                make.left.equalTo(self.coverView).offset(28);
            }];
        }
        self.coverView.hidden = YES;
    });
}
- (void)removeAllHelpView{
    [self.coverView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [self.coverView removeFromSuperview];
}

- (void)removeHelpView{
    [self.coverView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [self.coverView removeFromSuperview];
    [[NSUserDefaults standardUserDefaults]setObject:@1 forKey:@"isFirstExercieseCard"];
    [[NSUserDefaults standardUserDefaults]synchronize];
}
- (void)setupTimer{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(addCardTimeCount) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    if (self.type == XHENETRCARDNORMAL) {
        // 开始
        [self.timer setFireDate:[NSDate date]];
    }else{
        // 暂停
        [self.timer setFireDate:[NSDate distantFuture]];
    }
}

- (void)addCardTimeCount{
    self.timeSource+=0.01;
    self.itemModel.cardTime = self.timeSource;
}

- (void)dealDataSource{
    NSMutableArray *sourceArr = [NSMutableArray array];
    __block NSMutableArray *itemArr = [NSMutableArray array];
    __block NSMutableArray *titleArr  = [NSMutableArray array];
    [self.itemModel.resultArray enumerateObjectsUsingBlock:^(ExercieseQuestionItemModel  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.type.intValue == 0) {
            [sourceArr addObject:itemArr];
            itemArr = [NSMutableArray array];
            [titleArr addObject:obj];
        }else{
            [itemArr addObject:obj];
        }
    }];
    [sourceArr addObject:itemArr];
    if (sourceArr.count > 0) {
        [sourceArr removeObjectAtIndex:0];
    }
    ExercieseQuestionItemModel *item = self.itemModel.resultArray.firstObject;
    self.mainTitle.text = item.paperName;
    self.sourceArray = sourceArr;
    self.titleArray = titleArr;
    
    self.confirmBtn.hidden = self.type == XHENTERCARDRESULT;
    
    [self.collectionView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.confirmBtn.mas_top).offset(self.confirmBtn.hidden?0:-16.f);
    }];
    
    
    [self.confirmBtn mas_updateConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11,*)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(self.confirmBtn.hidden?0:(-(16 + GK_SAVEAREA_BTM)));
        }else{
            make.bottom.equalTo(self.view.mas_bottom).offset(self.confirmBtn.hidden?0:(-(16 + GK_SAVEAREA_BTM)));
        }
        make.height.mas_equalTo(self.confirmBtn.hidden?0:44.0f);
    }];
    
    [self.collectionView reloadData];
}

- (void)updateCardItemStatus{
    if (![[[NSUserDefaults standardUserDefaults]objectForKey:@"isFirstExercieseCard"]boolValue]) {
        self.coverView.hidden = NO;
    }
    // 开始计时
    [self.timer setFireDate:[NSDate date]];
    // 处理数据
    [self dealDataSource];
}

- (void)updateCoverViewStatus{
    if (![[[NSUserDefaults standardUserDefaults]objectForKey:@"isFirstExercieseCard"]boolValue]) {
        self.coverView.hidden = NO;
    }
}
- (void)stopTime{
    [self.timer setFireDate:[NSDate distantFuture]];
}
- (void)startTime{
    [self.timer setFireDate:[NSDate date]];
}


#pragma mark - confirmMethod
- (void)confirmMethod{
    
    self.argModel.userId = [RPAppManager getCustomerId];
    NSMutableArray *arr = [NSMutableArray array];

    // 首先判断是否打完题
    __block BOOL isAll = YES;
    __block CGFloat totalTime = 0;
    __block CGFloat otherTime = 0;
    [self.itemModel.resultArray enumerateObjectsUsingBlock:^(ExercieseQuestionItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        self.argModel.id = obj.paperId;
        if (obj.type.intValue > 0) {
            ExercieseCardAnswerModel *model = [[ExercieseCardAnswerModel alloc]init];
            model.questionId = obj.id;
            model.doTime = @(ceil(obj.answerTime));
            totalTime+=ceil(obj.answerTime);
            if (obj.type.intValue == 1) {
                // 判断是否有选中项
                [obj.items enumerateObjectsUsingBlock:^(ExercisesQuestionChoiceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (obj.isSelected) {
                        model.content = obj.prefix;
                        *stop = YES;
                    }
                }];
                // 判断是否为空
                if (model.content.length == 0) {
                    isAll = NO;
                }
            }
            [arr addObject:model];
        }else{
            otherTime += obj.answerTime;
        }
    }];
  
    self.argModel.answerItems = arr;
    // 试题+目录页+答题卡
    self.argModel.doTime = @(ceil(totalTime + otherTime + self.itemModel.cardTime));

    
    NSString *message = @"";
    // 已经全部选中
    if (isAll) {
        message = @"本次练习已全部作答";
    }else{
        message = @"本次练习还有题目未作答";
    }
    __weak typeof(self)weakSelf = self;
    ExercisesNormalAlertView *alertView = [[ExercisesNormalAlertView alloc]initWithAlertTitle:@"确认交卷？" message:message confirmTitle:@"交卷" cancelTitle:@"取消" confirmAciton:^{
        __strong typeof(weakSelf)strongSelf = weakSelf;
        // 处理数据
        [strongSelf sendPaperSource];
        
    } cancelAction:^{

    }];
    [alertView show];

    // 判断是否有未作答的题目

}

- (void)sendPaperSource{
    
    // 停止播放
    [self.timer invalidate];
    // 销毁
    self.timer = nil;

    
    [WHToast showImage:[UIImage imageNamed:@"toast_tag_loading"] message:@"正在提交..." duration:2 finishHandler:nil];
    
    NSDictionary *dict = [self.argModel mj_keyValues];

    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(PostAnswerSubmit) parames:dict success:^(id responseObj) {
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"lessonId"] = [[NSUserDefaults standardUserDefaults]objectForKey:@"currentLessonId"];
        param[@"userId"] = self.argModel.userId;
        param[@"md5"] = [RPAppManager md5StrWithApi:GetUserAnswer];
        [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetUserAnswer) parames:param success:^(id responseObj) {
            [WHToast hide];
            ExercisesPaperResultModel *resultModel = [ExercisesPaperResultModel mj_objectWithKeyValues:responseObj[RESPONSE]];
            [ExercisesPageModel deleteExercieseById:resultModel.paper.id];
            if (self.type == XHENTERCARDADD) {
                ExercisesAnswerResultViewController *resultVC = [[ExercisesAnswerResultViewController alloc]init];
                resultVC.isFinishVideo = self.isVideoFinish;
                resultVC.dtlModel = resultModel;
                [self.navigationController pushViewController:resultVC animated:YES];
            }else{
                [self dismissViewControllerAnimated:YES completion:nil];
                if (self.backResultCard) {
                    self.backResultCard(resultModel);
                }
            }
            [[NSNotificationCenter defaultCenter] postNotificationName:@"updateAboutQuestionSource" object:nil userInfo:@{@"isFinish":@1}];
            
        } failure:^(NSError *error) {
            [WHToast showImage:[UIImage imageNamed:@"toast_tag_error"] message:error.userInfo[@"info"] duration:2 finishHandler:nil];
        }];

    } failure:^(NSError *error) {
        [WHToast showImage:[UIImage imageNamed:@"toast_tag_error"] message:error.userInfo[@"info"] duration:2 finishHandler:nil];
                 
    }];
}

#pragma mark - collectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return self.titleArray.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    NSArray *arr = self.sourceArray[section];
    return arr.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ExercieseQuestionItemModel *model = self.sourceArray[indexPath.section][indexPath.row];
    ExercisesAnswerCardItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ExercisesAnswerCardItemCell" forIndexPath:indexPath];
    [cell setCartItem:model indexPath:indexPath];
    cell.delegate = self;
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    if (kind == UICollectionElementKindSectionHeader) {
        ExercisesAnswerCardHeaderView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"ExercisesAnswerCardHeaderView" forIndexPath:indexPath];
        ExercieseQuestionItemModel *model = self.titleArray[indexPath.section];
        NSArray *sourceDatas = self.sourceArray[indexPath.section];
        if (sourceDatas.count != 0) {
            [header setCardHeadTitle:model.subName];
        }else{
            [header setCardHeadTitle:@""];
        }
        return header;
    }
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(38, 38);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(16, 16, 16, 16);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 16.0f;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 26.0f;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    NSArray *sourceDatas = self.sourceArray[section];
    if (sourceDatas.count != 0) {
        return CGSizeMake(kScreenW, 32);
    }else{
        return CGSizeZero;
    }
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    return CGSizeZero;
}
#pragma mark - ExercisesAnswerCardItemCellDelegate
- (void)didSelectedAtIndexPath:(NSIndexPath *)indexPath{
   
    
    if (self.type != XHENTERCARDADD) {
        [self dismissViewControllerAnimated:YES completion:nil];
        
    }
    ExercieseQuestionItemModel *model = self.sourceArray[indexPath.section][indexPath.row];
    if (self.done) {
        self.done(model);
    }
}

@end
